/*
 * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.sun.max.vm.stack;

import static com.sun.max.vm.compiler.target.Stub.Type.*;

import com.sun.max.unsafe.*;
import com.sun.max.vm.actor.member.*;
import com.sun.max.vm.compiler.target.*;
import com.sun.max.vm.jni.*;
import com.sun.max.vm.reflection.*;
import com.sun.max.vm.thread.*;

/**
 * Utility for iterating over the source method frames (or 'vframes' in HotSpot terminology)
 * of a call stack. In this context, a source method is a <i>bytecode method</i> (which
 * may or may not have been compiled from Java source code) either loaded by the VM
 * from a class file or generated by the VM (e.g. a {@linkplain NativeStubGenerator native
 * method stub} or a {@linkplain InvocationStubGenerator reflection invocation stub}).
 */
public class SourceFrameVisitor extends RawStackFrameVisitor implements TargetMethod.CodePosClosure {

    public SourceFrameVisitor() {
    }

    /**
     * Iterates over a given stack, calling {@link #visitSourceFrame(ClassMethodActor, int, boolean, long)}
     * for each source method with an activation frame on the stack.
     */
    public void walk(StackFrameWalker walker, Pointer ip, Pointer sp, Pointer fp) {
        if (walker == null) {
            walker = new VmStackFrameWalker(VmThread.current().tla());
        }
        walker.inspect(ip, sp, fp, this);
    }

    @Override
    public boolean doCodePos(ClassMethodActor method, int bci) {
        if (!visitSourceFrame(method, bci, trapped, frameId)) {
            stopped = true;
            return false;
        }
        trapped = false;
        frameId++;
        return true;
    }

    long frameId;
    boolean trapped;
    boolean stopped;

    @Override
    public boolean visitFrame(StackFrameCursor current, StackFrameCursor callee) {
        final TargetMethod targetMethod = current.targetMethod();
        if (targetMethod == null) {
            visitNativeFrame(current.nativeIP().toLong());
            return true;
        }
        if (targetMethod.classMethodActor == null) {
            // ignore stubs, trampolines, adapters etc
            return true;
        }

        // TODO this value is not stable in the face of deoptimzation as frames can move.
        frameId = current.sp().toLong() << 16;

        trapped = callee.targetMethod() != null && callee.targetMethod().is(TrapStub);
        stopped = false;
        int count = targetMethod.forEachCodePos(this, current.vmIP());
        if (count == 0 && !stopped) {
            return visitSourceFrame(targetMethod.classMethodActor, -1, trapped, frameId);
        }
        return !stopped;
    }

    /**
     * Notifies this object of a source method frame being traversed.
     *
     * @param method a source method on the stack
     * @param bci the bytecode index of the execution point within the method (or -1 if not available)
     * @param trapped specifies if execution is stopped in {@code method} at a trap
     * @param frameId a unique identifier for this activation of the method.
     *                This value is only valid while the method activation is on the stack AND
     *                its immediate callee (if any) is also on the stack.
     * @return {@code true} if the stack walk should continue
     */
    public boolean visitSourceFrame(ClassMethodActor method, int bci, boolean trapped, long frameId) {
        return true;
    }

    /**
     * Notifies this object of one or more native/C functions being traversed.
     *
     * @param frameId a unique identifier for the set of native/C functions frames
     * @return {@code true} if the stack walk should continue
     */
    public boolean visitNativeFrame(long frameId) {
        return true;
    }
}
